package com.jeady.timetodo.activities.lock

import android.app.admin.DevicePolicyManager
import android.content.ComponentName
import android.content.ContentValues
import android.content.Context
import android.content.Intent
import android.util.Log
import android.widget.Toast
import androidx.activity.result.ActivityResultLauncher
import androidx.compose.runtime.mutableStateOf
import androidx.core.content.ContextCompat.getSystemService

class ScreenController {
    companion object {
        private var devicePolicyManager: DevicePolicyManager?=null
        var hasLockPermission = mutableStateOf(false)
        private var adminCompName: ComponentName?=null
        private var _screenController: ScreenController?=null
        fun getInstance(context: Context): ScreenController? {
            _screenController?.let{
                return _screenController
            } ?: run {
                _screenController = ScreenController()
            }
            _screenController?.apply {
                getSystemService(context, DevicePolicyManager::class.java)?.let {
                    devicePolicyManager = it
                    adminCompName = ComponentName(context, DeviceAdmin::class.java)
                    adminCompName?.let { admin ->
                        hasLockPermission.value = it.isAdminActive(admin)
                    }
                }
                return _screenController!!
            }
            return null
        }
    }

    fun enablePhone(context: Context, launcherGrantLock: ActivityResultLauncher<Intent>) {
        val active = adminCompName?.let { devicePolicyManager?.isAdminActive(it) }
        Log.e(ContentValues.TAG, "enablePhone: get active : $active")
        if (active==true) {
            adminCompName?.let { devicePolicyManager?.removeActiveAdmin(it) }
            hasLockPermission.value = false
        } else {
            val intent = Intent(DevicePolicyManager.ACTION_ADD_DEVICE_ADMIN)
            intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN, adminCompName)
            intent.putExtra(DevicePolicyManager.EXTRA_ADD_EXPLANATION, "用于锁定屏幕")
//            startActivityForResult(intent, RESULT_ENABLE)
//            startActivity(context, intent, null)
            launcherGrantLock.launch(intent)
        }
    }

    fun lockActive(): Boolean{
        return adminCompName?.let { devicePolicyManager?.isAdminActive(it) } == true
    }

    fun lockPhone(context: Context) {
        try {
            devicePolicyManager?.lockNow()
//            dm.setMaximumTimeToLock(adminCompName, (schedulerInterval*1000).toLong())
        } catch (ex: SecurityException) {
            Toast.makeText(context, "未授权", Toast.LENGTH_SHORT).show()
        }
    }
}